/*********确认订单*********/
var comfirmOrder = {
    conData: {}, //公共数据
    jsons: [], //数据Json
    address: [], //收货地址
    actRes: -1, //操作结果 -2-程序出错 -1-无操作 0-下单失败(全部失败) 1-成功 2-未选择收货地址 3-数据被篡改 4-用户未登录 5-不允许提交空数据 6-不允许站外提交 7-购物车为空 8-部分成功
    postData: {}, //提交json格式数据
    resJson: {}, //操作结果(用于回调提示Json),actRes为0或8时可使用该json详细说明错误
    addressid: '', //收货地址ID
    opensummuntiy: true,
    //显示收货地址
    showAddress: function () {
        if (comfirmOrder.conData.iswxpay == 1) {
            $("#wxAdress").show();
        }
        else {
            $("#wxAdress").hide();
        }
        var h = '';
        if (!comfirmOrder.address || comfirmOrder.address.length == 0) {
            $('#noaddress').show().click(function () {
                if ($("#addaddress").css("display") == "none") {
                    $('#s_area').click(function () {
                        addressset.giveFocus($('#street').val().length == 0 ? $('#city').val() : $('#street').val(), comfirmOrder.conData.comid);
                    });
                    $("#addaddress").show();
                }
                else if ($("#addaddress").css("display") != "none") {
                    $("#addaddress").css("display", "none");
                }
            });
        } else {
            if ($("#addaddress").css("display") != "none") $("#addaddress").css("display", "none");
            for (var i = 0; i < comfirmOrder.address.length; i++) {
                var fulladdress = comfirmOrder.address[i].fullarea + ' ' + comfirmOrder.address[i].communityname + ' ' + comfirmOrder.address[i].building + ' ' + comfirmOrder.address[i].address;
                if (fulladdress.length > 17) {
                    fulladdress = fulladdress.substring(0, 17) + "...";
                }
                h += '<li' + (i == 0 ? ' class="curr"' : ' class="hide"') + ' dex="' + i + '" sourceType="0" addressid="' + comfirmOrder.address[i].id + '" userid="' + comfirmOrder.address[i].userid + '" areacode="' + comfirmOrder.address[i].areacode + '" onclick="comfirmOrder.addressChange(this);">';
                h += '  <div class="pmname"><a>' + comfirmOrder.address[i].name + '（' + (comfirmOrder.address[i].mobile ? comfirmOrder.address[i].mobile : comfirmOrder.address[i].phone) + '）</a></div>';
                h += '  <div class="pmaddress">';
                h += '      <p>' + fulladdress + '<a href=\"#\" onclick=\"comfirmOrder.addressEdit(\'' + comfirmOrder.address[i].id + '\')\">[编辑]</a></p>';
                h += '  </div>';
                h += '</li>';
            }
        }
        $('#address').show().html(h);
    },
    //显示购物车商品
    showCart: function () {
        for (var i = 0; i < comfirmOrder.jsons.length; i++) {
            var isCod = true; //所有商品都支持时才支持货到付款
            var codFee = 0; //货到付款手续费

            //商品列表
            var _proHtml = '';
            var _proNum = 0;
            for (var j = 0; j < comfirmOrder.jsons[i].items.length; j++) {
                if (!comfirmOrder.jsons[i].items[j].isopencommunity) {
                    comfirmOrder.opensummuntiy = false
                }
                codFee += comfirmOrder.jsons[i].items[j].codfee;
                if (!comfirmOrder.jsons[i].items[j].cod) isCod = false;

                _proHtml += '<li id="li_' + comfirmOrder.jsons[i].items[j].id + '">';
                _proHtml += '  <div class="le">';
                _proHtml += '      <div><a><img src="' + comfirmOrder.jsons[i].items[j].pic + '" /></a></div>';
                _proHtml += '      <div class="le_price"><span>￥' + comfirmOrder.jsons[i].items[j].price + '</span></div>';
                _proHtml += '  </div>';
                _proHtml += '  <div class="ri">';
                _proHtml += '      <div class="title">' + comfirmOrder.jsons[i].items[j].proname + '</div>';
                if (comfirmOrder.jsons[i].items[j].skutext)
                    _proHtml += '  <div class="format">' + comfirmOrder.jsons[i].items[j].skutext + '</div>';
                _proHtml += '      <div class="ritext">数量<i class="maohao">:</i>' + comfirmOrder.jsons[i].items[j].num + '&nbsp;&nbsp;小计<i class="maohao">:</i><span>￥' + comfirmOrder.jsons[i].items[j].price * comfirmOrder.jsons[i].items[j].num + '</span></div>';
                _proHtml += '  </div>';
                _proHtml += '  <div class="clear"></div>';
                _proHtml += '</li>';

                _proNum += comfirmOrder.jsons[i].items[j].num;
            }
            $('#itemContainer ul').append(_proHtml);
            $('#cartNum').html(_proNum);

            //配送方式
            var youFei = 0;
            var _delHtml = '';
            if (comfirmOrder.jsons[i].isfree == 1 || comfirmOrder.jsons[i].isfree == -1 || (comfirmOrder.jsons[i].mailfee <= 0 &&
                comfirmOrder.jsons[i].expressfee <= 0 && comfirmOrder.jsons[i].emsfee <= 0)) {//免运费
                _delHtml += '<option value="2" payfee="0" total="' + comfirmOrder.jsons[i].proamount + '">' + (comfirmOrder.jsons[i].isfree == -1 ? '全场包邮' : '免运费') + '</option>';
            } else {
                var _delOptNum = 0;
                if (comfirmOrder.jsons[i].communtiyfee && comfirmOrder.opensummuntiy) {
                    if (!youFei) youFei = comfirmOrder.jsons[i].expressfee;
                    _delHtml += '<option value="5" payfee="' + comfirmOrder.jsons[i].communtiyfee + '" total="' + (comfirmOrder.jsons[i].proamount + comfirmOrder.jsons[i].communtiyfee) + '">楼宇配送<i class="maohao">:</i>￥' + comfirmOrder.jsons[i].communtiyfee + '</option>';
                    _delOptNum++;
                }
                if (comfirmOrder.jsons[i].mailfee) {
                    youFei = comfirmOrder.jsons[i].mailfee;
                    _delHtml += '<option value="1" payfee="' + comfirmOrder.jsons[i].mailfee + '" total="' + (comfirmOrder.jsons[i].proamount + comfirmOrder.jsons[i].mailfee) + '">平邮<i class="maohao">:</i>￥' + comfirmOrder.jsons[i].mailfee + '</option>';
                    _delOptNum++;
                }
                if (comfirmOrder.jsons[i].expressfee) {
                    if (!youFei) youFei = comfirmOrder.jsons[i].expressfee;
                    _delHtml += '<option value="2" payfee="' + comfirmOrder.jsons[i].expressfee + '" total="' + (comfirmOrder.jsons[i].proamount + comfirmOrder.jsons[i].expressfee) + '">快递<i class="maohao">:</i>￥' + comfirmOrder.jsons[i].expressfee + '</option>';
                    _delOptNum++;
                }

                if (comfirmOrder.jsons[i].emsfee) {
                    if (!youFei) youFei = comfirmOrder.jsons[i].emsfee;
                    _delHtml += '<option value=="3" payfee="' + comfirmOrder.jsons[i].emsfee + '" total="' + (comfirmOrder.jsons[i].proamount + comfirmOrder.jsons[i].emsfee) + '">EMS<i class="maohao">:</i>￥' + comfirmOrder.jsons[i].emsfee + '</option>';
                    _delOptNum++;
                }
                if (_delOptNum)
                    _delHtml = '<option value="" payfee="0" total="' + comfirmOrder.jsons[i].proamount + '">配送方式</option>' + _delHtml;
            }
            $('#select_delivery').append(_delHtml).change(function () {
                $('#cartAmount').html($('#select_delivery option:selected').attr('total'));
            });
            //支付方式
            var _payHtml = '';
            for (var j = 0; j < comfirmOrder.jsons[i].payments.length; j++) {
                _payHtml += '<option value="' + comfirmOrder.jsons[i].payments[j].payid + '" payfee="' + comfirmOrder.jsons[i].payments[j].fee + '">' + comfirmOrder.jsons[i].payments[j].payname + '</option>';
            }
            if (isCod)
                _payHtml += '<option value="0" payfee="' + codFee + '">货到付款</option>';
            if (comfirmOrder.jsons[i].payments.length > 1 || (comfirmOrder.jsons[i].payments.length && isCod))
                _payHtml = '<option value="-1" payfee="0">支付方式</option>' + _payHtml;
            $('#select_payment').append(_payHtml);

            $('#cartAmount').html($('#select_delivery option:selected').attr('total'));

            //发票
            if (comfirmOrder.jsons[i].invoice && comfirmOrder.jsons[i].invoice == "1") {
                $('#invoice_container').show();
            }
        }
    },
    //加载
    load: function () {
        $(function () {
            if (!comfirmOrder.jsons || comfirmOrder.jsons.length == 0) {
                window.location = '/cart.shtml?comid=' + comfirmOrder.conData.comid; //跳转回购物车
            }

            if (comfirmOrder.jsons && comfirmOrder.jsons.length > 0) {
                comfirmOrder.showAddress();
                comfirmOrder.showCart();
                $('#select_delivery').change(comfirmOrder.delChange);
            }

            //结算
            $('#btnEnter').click(function () {
                if ($("#select_delivery").val() == 3) {
                    var _should = comfirmOrder.shouldArea(comfirmOrder.conData.comid, comfirmOrder.conData.memberid, $("#address li.curr").attr("addressid"), $("#address li.curr").attr("areacode"));
                    if (_should == 1) {
                        $.Alert('请先编辑地址选择您所在的配送小区', 160);
                        return;
                    } else if (_should == 3) {
                        $.Alert('超出小区配送范围', 160);
                        return;
                    }
                }
                if (comfirmOrder.jsons && comfirmOrder.jsons.length > 0) {
                    if ($.CheckSubmit.submit(comfirmOrder.saveCheck()))
                        document.forms["form1"].submit(); //确认订单
                }
            });

            if (comfirmOrder.actRes != -1 && comfirmOrder.actRes != 1) {
                $.Alert('下单失败，请稍后再试...', 160);
            }
        });
        //选择省份
        var last = false;
        $("#pvid").change(function () {
            if (this.value.length > 0) {
                $("#city").get(0).options.length = 1;
                $("#street").get(0).options.length = 1;
                comfirmOrder.clearBuilding();
                comfirmOrder.showDistrict('city', this.value);
                last = false;
            }
        });
        //选择城市
        $("#city").change(function () {
            if (this.value.length > 0) {
                if (!last) {
                    $("#street").parent().show();
                    $("#street").get(0).options.length = 1;
                    comfirmOrder.clearBuilding();
                    comfirmOrder.showDistrict('street', this.value);
                    if ($("#street").get(0).options.length <= 1) {
                        last = true;
                    }
                }
                if (last) {
                    $("#street").parent().hide();
                    addressset.showCommuntiy(this.value, d.cid, '', false, false);
                }
            }
        });
        //选择地区
        $("#street").change(function () {
            if (this.value.length > 0) {
                comfirmOrder.clearBuilding();
                addressset.showCommuntiy(this.value, d.cid, '', false, false);
            }
        });
        comfirmOrder.showDistrict('pvid', '0');
        //编辑地址提交数据
        $("#addsubmit").click(function () {
            //验证收件人姓名
            var txtName = $('#txtName').val();
            if (txtName.length < 1) {
                $.Alert('请输入收件人姓名', 160); return;
            }
            //验证地区
            if ($('#pvid').val().length > 0) {
                if ($('#city').val().length > 0) {
                    if ($('#street').val().length == 0 && $("#street").get(0).options.length > 1) {
                        $.Alert('请选择地区', 160); return false;
                    } else {
                        var __area = '';
                        if ($("#communityid").val()) {
                            __area = $("#communityid").val();
                        }
                        if ($("#community").css("display") != 'none' && __area == "") {
                            $.Alert('请选择小区', 160); return false;
                        }
                        else {
                            $('#hDistrict').val($('#street').val().length == 0 ? $('#city').val() : $('#street').val());
                            $("#street").get(0).options.length = 1; //不清除的话区会出现重复项
                        }
                    }
                } else {
                    $.Alert('请选择城市', 160); return false;
                }
            } else {
                $.Alert('请选择省份', 160); return;
            }
            //验证详细地址
            var address = $('#txtAddress').val();
            if (address.length < 1) {
                $.Alert('请输入详细地址', 160); return false;
            }
            //验证手机号码
            var mobile = $('#txtMobile').val();
            if (mobile.length < 1) {
                $.Alert('请输入手机号码', 160);
                return;
            } else {
                var regx = /^(13|15|18|013|015|018)\d{9}$/;
                if (regx.exec(mobile) == null) {
                    $.Alert('手机号码错误', 160);
                    return;
                }
            }
            var pvid = $('#pvid').val();
            var city = $('#city').val();
            var street = $('#street').val();
            var communityid = $('#communityid').val();
            var hbuilding = $('#hbuilding').val();
            var chkisdefult = $('#chkisdefult').attr("checked");
            var hDistrict = $('#hDistrict').val();
            $.ajax({
                type: "POST",
                url: "/ajax/District.ashx",
                dataType: 'json',
                async: false,
                data: { "act": "addaddress", "name": txtName, "hDistrict": hDistrict, "address": address, "mobile": mobile, "pvid": pvid, "city": city, "street": street, "communityid": communityid, "hbuilding": hbuilding, "chkisdefult": chkisdefult, "memberid": comfirmOrder.conData.memberid, "addressid": comfirmOrder.addressid },
                success: function (msg) {
                    if (msg != '0') {
                        $.Alert('操作成功', 160);
                        window.location.reload();
                        window.location = '/WxPay/Confirm.aspx?comid=' + comfirmOrder.conData.comid; //确认订单
                    }
                },
                error: function (error) { $.Alert('操作失败', 160); }
            });
            $("#addaddress,#noaddress").hide();
            //comfirmOrder.loadAddress(comfirmOrder.conData.comid, comfirmOrder.conData.memberid);
        });
        //addressid
        if (comfirmOrder.address.length > 0) {
            comfirmOrder.addressid = comfirmOrder.address[0].id;
        }

    },
    //表单提交验证
    saveCheck: function () {
        if ($("#noaddress").css("display") != 'none' || $(".curr").length == 0) {
            $.Alert('请选择送货地址');
            return false;
        }
        if (!$('#select_delivery option').length || $('#select_delivery').val() == '') {
            $.Alert('请选择配送方式');
            return false;
        }
        if (!$('#select_payment option').length || $('#select_payment').val() == '-1') {
            $.Alert('请选择支付方式');
            return false;
        }
        var s = ''; //保存的json格式数据
        s += '{';
        s += '"comid":"' + comfirmOrder.conData.comid + '",';
        s += '"delcode":"' + $('#select_delivery').val() + '",';
        s += '"payid":"' + $('#select_payment').val() + '",';

        //----- 发票：Start --
        if (comfirmOrder.jsons[0].invoice && $('#chkInvoice')[0].checked) {
            var invoiceTitle = $.trim($('#txtInvoice').val());
            if (invoiceTitle.length == 0) {
                $.Alert('请输入发票抬头');
                return false;
            }
            s += '"invoice":"1",';
            s += '"invoiceTitle":"' + invoiceTitle + '"';
        }
        else {
            s += '"invoice":"0"';
        }
        //----- 发票：End --

        s += '}';
        if ($('#address li.curr').attr('sourceType') == 1) {
            var data = '{';
            data += '"sourceType":"' + $('#address li.curr').attr('sourceType') + '",'; //地址来源
            data += '"areacode":"' + $('#address li.curr').attr('areacode') + '",'; //地区编码
            data += '"userName":"' + $('#address li.curr div.pmname').attr('userName') + '",'; //姓名
            data += '"telNumber":"' + $('#address li.curr div.pmname').attr('telNumber') + '",'; //电话
            data += '"provice":"' + $('#address li.curr div.pmaddress').attr('provice') + '",'; //省
            data += '"city":"' + $('#address li.curr div.pmaddress').attr('city') + '",'; //市
            data += '"counties":"' + $('#address li.curr div.pmaddress').attr('counties') + '",'; //区
            data += '"detail":"' + $('#address li.curr div.pmaddress').attr('detail') + '",'; //详细信息
            data += '"postalcode":"' + $('#address li.curr div.pmaddress').attr('postalcode') + '",'; //邮编
            data += '"items":[' + s + ']';
            data += '}';
            $('#orderpars').val(data);
        }
        else
            $('#orderpars').val('{"addressid":"' + $('#address li.curr').attr('addressid') + '","sourceType":"' + $('#address li.curr').attr('sourceType') + '","items":[' + s + ']}');
        return true; ;
    },
    //选择配送方式
    delChange: function () {
        $('#cartAmount').html($(this).attr('total'));
    },
    //选择地址
    addressChange: function (obj) {
        comfirmOrder.wxAddress = $("#wxaddress").html();
        if (comfirmOrder.address.length < 1) return;
        var $this = $(obj);
        var $p = $this.parent();
        if ($this.hasClass('curr')) {
            $this.removeClass('curr');
            $p.find('li').show();
            if ($('#select_delivery option:selected').attr('value') == 5) {
                $("#wxadd").hide();
            }
        } else {
            var userid = $this.attr('userid');
            var areacode = $this.attr('areacode');
            var comid = comfirmOrder.conData.comid;
            $p.find('li').not($this).hide();
            $this.addClass('curr');
        }
    },
    invoiceChange: function (obj) {
        if (obj.checked)
            $('#txtInvoice').show();
        else
            $('#txtInvoice').hide();
    },
    //编辑地址绑定数据
    addressEdit: function (aid) {
        for (var i = 0; i < comfirmOrder.address.length; i++) {
            if (comfirmOrder.address[i].id == aid) {
                comfirmOrder.addressid = aid;
                if (comfirmOrder.address[i].name) $('#txtName').val(comfirmOrder.address[i].name);
                if (comfirmOrder.address[i].mobile) $('#txtMobile').val(comfirmOrder.address[i].mobile);
                if (comfirmOrder.address[i].address) $('#txtAddress').val(comfirmOrder.address[i].address);
                if (comfirmOrder.address[i].areacode) $('#hDistrict').val(comfirmOrder.address[i].areacode);
                if (comfirmOrder.address[i].isdefault) $('#chkisdefult').attr("checked", 'true');
                if (comfirmOrder.address[i].building) $('#hbuilding').val(comfirmOrder.address[i].building);
                if (comfirmOrder.address[i].building) $('#communityid').val(comfirmOrder.address[i].communityid);
                if (comfirmOrder.address[i].communityname) { $('#community').show(); $('#s_area').val(comfirmOrder.address[i].communityname + ' ' + comfirmOrder.address[i].building) }
                if (comfirmOrder.address[i].province) {
                    comfirmOrder.setSelected($('#pvid'), comfirmOrder.address[i].province);
                    if (comfirmOrder.address[i].city) comfirmOrder.showDistrict('city', $('#pvid').val());
                }
                if (comfirmOrder.address[i].city) {
                    comfirmOrder.setSelected($("#city"), comfirmOrder.address[i].city);
                    if (comfirmOrder.address[i].region) comfirmOrder.showDistrict('street', $("#city").val());
                }
                if (comfirmOrder.address[i].region) {
                    comfirmOrder.setSelected($('#street'), comfirmOrder.address[i].region);
                } else {
                    $('#street').parent().hide();
                }
                if (comfirmOrder.shouldArea(comfirmOrder.conData.comid, comfirmOrder.conData.memberid, comfirmOrder.address[i].id, comfirmOrder.address[i].areacode) == 1) {
                    $("#community").show();
                }
                var areacode = comfirmOrder.address[i].areacode;
                addressset.havearea(areacode, cid);
                $('#s_area').click(function () {
                    addressset.giveFocus($('#street').val().length == 0 ? $('#city').val() : $('#street').val(), comfirmOrder.conData.comid);
                });
            }
        }
        $('#address').hide();
        $('#wxAdress').hide();
        $("#addaddress").show();
    },
    //是否需要完善小区信息
    shouldArea: function (comid, userid, addressid, areacode) {
        var result;
        $.ajax({
            type: 'POST',
            url: '/ajax/Cart.ashx',
            dataType: 'json',
            data: { "act": "shouldarea", "comid": comid, "userid": userid, "addressid": addressid, "areacode": areacode },
            async: false,
            success: function (msg) {//msg:0:用户已经设置送货小区   msg:1:商家设置有送货小区，但用户尚未选择收货小区   msg:2:收货地址ID错误   msg:3:商家尚未在改地区设置送货小区
                result = msg;
            }
        });
        return result;

    },
    //加载省市区
    showDistrict: function (elemId, disId) {
        var s = document.getElementById(elemId);
        if (!s) return;
        $.ajax({
            type: 'POST',
            url: '/ajax/Cart.ashx',
            dataType: 'json',
            data: { "act": "getdistrict", "pid": disId },
            async: false,
            success: function (msg, textStatus) {
                for (var i = 0; i < msg.length; i++) {
                    var t = document.createElement("option");
                    t.text = msg[i].C_ftitle;
                    t.value = msg[i].C_fid;
                    s.add(t);
                }

            },
            error: function (textStatus) { $.Alert("error:" + textStatus); }
        });
    },
    //清除指定项
    clearSelect: function (obj) {
        var l = obj.options.length;
        for (var i = 0; i < l; i++) {
            if (i > 0) obj.remove(l - i); //清空
        }
    },
    //选中指定项
    setSelected: function (s, val) {
        var $this = $(s);

        for (var i = 0; i < $this.get(0).options.length; i++) {
            if ($this.get(0).options[i].value == val) {
                $this.get(0).options[i].selected = true;
            }
        }
    },
    //重新加载地址列表
    loadAddress: function (comid, memberid) {
        $.ajax({
            type: "POST",
            url: "/ajax/District.ashx",
            dataType: 'json',
            async: false,
            data: { "act": "getaddresslist", "comid": comid, "memberid": memberid },
            success: function (msg) {
                comfirmOrder.address = msg;
                comfirmOrder.showAddress();
            },
            error: function (error) { $.Alert('操作失败', 160); }
        });
    },

    clearBuilding: function () {
        $('#s_area').val('');
        $("#communityid").val('');
        $("#hbuilding").val('');
    }
}


    